package org.ws.edu.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

public class MenuDispatcher {

	private ConsoleHandlerUI mConsoleHandler = null;

	/**
	 * Object of Logger.
	 */
	private static Logger logger = Logger.getLogger(MenuDispatcher.class);
	private final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

	public MenuDispatcher(ConsoleHandlerUI handler) {
		mConsoleHandler = handler;
	}

	public void run() {
		try {
			while (true) {
				try {
					String[] menu = { "Available Tests", "Invalid Tests", "Help", "Exit", };
					for (int i = 0; i < menu.length; i++) {
						System.out.println(i + 1 + ". " + menu[i]);
					}

					System.out.println("Enter the number of operation...");
					int numberOfOperation = Integer.parseInt(in.readLine()) - 1;

					switch (numberOfOperation) {

						case 0:
							mConsoleHandler.chooseTest();
							mConsoleHandler.handle();
							logger.info("Switch \"Available Tests\" element of menu");
							break;

						case 1:
							mConsoleHandler.getInvalidTestNames();
							System.out.println();
							logger.info("Switch \"Invalid Tests\" element of menu");
							break;

						case 2:
							mConsoleHandler.getHelp();
							System.out.println();
							logger.info("Switch \"Help\" element of menu");

							break;
						case 3:
							mConsoleHandler.exitServerThread();
							System.exit(0);
							logger.info("Close program");
							break;
					}
				} catch (IOException e) {
					logger.warn("Can't read from System.in stream", e);
				} catch (NumberFormatException e) {
					logger.info("Incorrect test number", e);
					continue;
				}
			}
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				logger.warn("Can't close stream", e);
			}
		}
	}
}
